<?php

class CandidateGroupsController extends AppController
{

	public $name = 'CandidateGroups';
	public $helpers = array();
	public $uses = array('CandidateGroup');

	public $modelName = '';
	public $po_domain = '';
	public $url_part  = '';

	function beforeFilter()
	{
		parent::beforeFilter();

		$this->modelName = Inflector::singularize($this->name);
		$this->po_domain = Inflector::underscore($this->name);
		$this->url_part  = 'candidates/groups';
		$this->set('po_domain', $this->po_domain);
		$this->set('url_part',  $this->url_part);
		$this->set('modelName', $this->modelName);
		$this->set('PKName',    $this->{$this->modelName}->primaryKey);
        Auth::Access('(admin | (client_admin & CANDIDATES)) & active');
	}

	function create()
	{
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		if (!empty($this->data[$modelName]['submit_back'])) {
            $this->redirect("/{$url_part}/", null, true);
            exit();
	    }
		$this->set('mode', __FUNCTION__);

	    $this->pageTitle = strip_tags(__d($po_domain, 'create_title', true));

	    $submit = !empty($this->data);
		if (! $this->{$modelName}->allowUpdate()) {
		    $this->data = array($modelName => array());
		}
		if ($this->{$modelName}->allowUpdate() && $submit) {
			$error_msg = '';
			$success_msg = __d($po_domain, 'created', true);

            if (Auth::o()->is('client_admin')) {
                $auth_data =& Auth::o()->data();
                $this->data[$modelName]["client_id"] = $auth_data["client_id"];
            }

			$id = null;
            if (empty($error_msg)) {
				if ($this->{$modelName}->save($this->{$modelName}->create($this->data))) {
       			    $id = $this->{$modelName}->getInsertID();
       			    $this->data[$modelName][$PKName] = $id;
				} elseif (!empty($this->{$modelName}->validationErrors)) {
					$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
				} else {
	    		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
				}
            }
			if (empty($error_msg)) {
			    $this->msgNotice($success_msg);
			    $this->redirect("/{$url_part}/{$id}/", null, true);
			    exit();
			} else {
			    $this->msgError($error_msg, @$error_code);
			}
		}

		if (Auth::o()->is("admin")) {
		    $this->set("clients_list", $this->{$modelName}->getModel("Client")->generateList());
		}

		$this->data[$modelName]['__allows']['update'] = $this->{$modelName}->allowUpdate();
		$this->data[$modelName]['__allows']['delete'] = $this->{$modelName}->allowDelete();

		$this->render('details');
	}

	function list_of()
	{
		vendor('date');

	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		$this->pageTitle = strip_tags(__d($po_domain, 'list_title', true));

		vendor('contingencies');
		vendor('order_html');
		vendor('pagination_html');
		vendor('page_of_data');

		$contingencies = new Contingencies();
        $contingencies->model =& $this->{$modelName};
        $contingencies->expects = Auth::o()->is('admin') ? 'Client' : '';

        /////////////////////////////////////////////////////////////
        $ses_war_name = __CLASS__.':'.__FUNCTION__.'_filter';
        if (!empty($this->data['Filter'])) {
            if (!empty($this->data['Filter']['submit_reset'])) {
                unset($_SESSION[$ses_war_name]);
                unset($this->data['Filter']);
            } elseif (!empty($this->data['Filter']['submit_apply'])) {
            	$_SESSION[$ses_war_name] = $this->data['Filter'];
            }
        }
        $filter = isset($_SESSION[$ses_war_name]) ? $_SESSION[$ses_war_name] : array();
        if (empty($this->data['Filter'])) {
            $this->data['Filter'] = $filter;
        }
        /////////////////////////////////////////////////////////////
		$conds = array();
		$client_id = null;
        if (Auth::o()->is('client_admin')) {
            $auth_data =& Auth::o()->data();
            $client_id = $auth_data["client_id"];
        } elseif (!empty($filter['client_id'])) {
            $client_id = $filter['client_id'];
        }
        if (isset($client_id)) {
            $conds[]["`{$modelName}`.`client_id`"] = $client_id;
        }

        $contingencies->conditions = $conds;

        $appearence = new OrderHTML();
        $appearence->orderFields = array(
            'id' => "`{$modelName}`.`{$PKName}`",
            'name' => "`{$modelName}`.`name`",
        );
        if (Auth::o()->is('admin')) {
            $appearence->orderFields['client'] = "`Client`.`name`";
        }
        $appearence->defaultOrder = Order::parseString('name');
        $appearence->processParams();

        $pagination = new PaginationHTML();
        $pagination->defaultLimit = 20;
        $pagination->processParams();

        $list = new PageOfData($contingencies, $appearence, $pagination);

        foreach ($list->rows as &$row) {
            $row[$modelName]['__allows'] = array(
                'update' => $this->{$modelName}->allowUpdate($row[$modelName]),
                'delete' => $this->{$modelName}->allowDelete($row[$modelName]),
            );
            $row[$modelName]['__candidates'] = $this->{$modelName}->numCandidatesFor($row[$modelName][$PKName]);
        }

        if (Auth::o()->is('admin')) {
		    $this->set('clients_list', $this->{$modelName}->getModel('Client')->generateList());
        }
		$this->set('list', $list);
	}

	function details($id = null)
	{
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		if (!empty($this->data[$modelName]['submit_back'])) {
            $this->redirect("/{$url_part}/", null, true);
            exit();
	    }
		$this->set('mode', __FUNCTION__);
		$this->pageTitle = strip_tags(__d($po_domain, 'details_title', true));

	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
	    }

        $conds = array();
        $conds[]["`{$modelName}`.`{$PKName}`"] = $id;
        if (Auth::o()->is('client_admin')) {
            $auth_data =& Auth::o()->data();
            $conds[]["`{$modelName}`.`client_id`"] = $auth_data["client_id"];
        }

	    $this->{$modelName}->rel();
        $tmp = $this->{$modelName}->find($conds);

		if (! is_array($tmp) || !count($tmp)) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/", null, true);
			exit();
		}

		////// MENU ///////////////////////

	    $this->MainMenu->setActive($this->MainMenu->findItem("/{$url_part}/"));

		///////////////////////////////////

		$submit = !empty($this->data);
		if (! $this->{$modelName}->allowUpdate($tmp[$modelName])) {
		    $this->data = array($modelName => array());
		}
		foreach ($tmp as $_modelName => $_modelData) {
            if ($_modelName !== $modelName) {
    			$this->data[$_modelName] = $tmp[$_modelName];
            } else {
        		$this->data[$modelName] = am($tmp[$modelName], $this->data[$modelName]);
            }
		}

		if ($this->{$modelName}->allowUpdate($tmp[$modelName]) && $submit) {
			$error_msg = '';
			$success_msg = __d($po_domain, 'changed', true);

            if (Auth::o()->is('client_admin')) {
                $auth_data =& Auth::o()->data();
                $this->data[$modelName]["client_id"] = $auth_data["client_id"];
            }

            if (empty($error_msg)) {
				if ($this->{$modelName}->save($this->data)) {

				} elseif (!empty($this->{$modelName}->validationErrors)) {
					$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
				} else {
	    		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
				}
            }
			if (empty($error_msg)) {
			    $this->msgNotice($success_msg);
			    $this->redirect("/{$url_part}/{$id}/", null, true);
			    exit();
			} else {
			    $this->msgError($error_msg, @$error_code);
			}
		}

		if (Auth::o()->is("admin")) {
		    $this->set("clients_list", $this->{$modelName}->getModel("Client")->generateList());
		}
		$this->data[$modelName]['__allows']['update'] = $this->{$modelName}->allowUpdate($tmp[$modelName]);
		$this->data[$modelName]['__allows']['delete'] = $this->{$modelName}->allowDelete($tmp[$modelName]);
	}

	function remove($id = null)
	{
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
	    }
		if (!$id) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
		} else {
            $conds = array();
            $conds[]["`{$modelName}`.`{$PKName}`"] = $id;
            if (Auth::o()->is('client_admin')) {
                $auth_data =& Auth::o()->data();
                $conds[]["`{$modelName}`.`client_id`"] = $auth_data["client_id"];
            }
            $this->{$modelName}->rel();
		    $data = $this->{$modelName}->find($conds);
		    if (is_array($data) && count($data)) {
		    	if ($this->{$modelName}->allowDelete($data[$modelName])) {
	    		    if ($this->{$modelName}->del($id)) {
	    	       		$this->msgNotice(__d($po_domain, 'deleted', true));
	        		} else {

	        		}
		    	} else {
			        $this->msgError(__d(null, 'deny', true), @$error_code);
		    	}
		    } else {
		        $this->msgError(__d($po_domain, 'absent', true), @$error_code);
		    }
		}
		$this->redirect("/{$url_part}/", null, true);
		exit();
	}

    function manage()
    {
        Auth::Access('admin | CANDIDATES');
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		if (!empty($this->data[$modelName]['submit_back'])) {
            $this->redirect("/{$url_part}/", null, true);
            exit();
	    }
		$this->pageTitle = strip_tags(__d($po_domain, 'Candidates group administration', true));

        $conds = array();
	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
            $conds[]["`{$modelName}`.`{$PKName}`"] = $id;
	    }
        if (Auth::o()->is('client_admin')) {
            $auth_data =& Auth::o()->data();
            $conds[]["`{$modelName}`.`client_id`"] = $auth_data["client_id"];
        }
        $this->{$modelName}->rel();
	    $tmp = $this->{$modelName}->find($conds);

		if (! is_array($tmp) || !count($tmp)) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/", null, true);
			exit();
		}

		$this->data = $tmp;

		$Candidate = $this->{$modelName}->getModel('Candidate'); /* @var $Candidate Candidate */
		$Candidate->rel();
		$this->data[$modelName]['__candidates'] = $Candidate->findCount(array("`Candidate`.`candidate_group_id`" => $id));

		////// MENU ///////////////////////

	    $this->MainMenu->setActive($this->MainMenu->findItem("/{$url_part}/"));

		///////////////////////////////////

        $this->set('tests_list', $this->{$modelName}->getToolsToAppointFor($id));
        $this->set('in_progress_tests_list', $this->{$modelName}->getInProgressToolsFor($id));
        $this->set('appointed_tests_list', $this->{$modelName}->getAppointedToolsFor($id));
        $this->set('completed_tests_list', $this->{$modelName}->getCompletedToolsFor($id));
    }

    function apply_tool()
    {
        Auth::Access('admin | CANDIDATES');
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

        $conds = array();
	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
            $conds[]["`{$modelName}`.`{$PKName}`"] = $id;
	    }
        if (Auth::o()->is('client_admin')) {
            $auth_data =& Auth::o()->data();
            $conds[]["`{$modelName}`.`client_id`"] = $auth_data["client_id"];
        }
        $this->{$modelName}->rel();
	    $tmp = $this->{$modelName}->find($conds);

		if (! is_array($tmp) || !count($tmp)) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/", null, true);
			exit();
		}

		$client_id = $tmp[$modelName]["client_id"];

	    $tool_id = null;
	    if (isset($this->params['tool_id'])) {
	        $tool_id = $this->params['tool_id'];
	    }
		if (empty($tool_id)) {
			$this->msgError(__d('tests', 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/{$id}/manage/", null, true);
			exit();
		}

		if (! $this->{$modelName}->isAllowTestFor($id, $tool_id)) {
			$this->msgError(__d($po_domain, 'You don’t apply this tool', true), @$error_code);
			$this->redirect("/{$url_part}/{$id}/manage/", null, true);
			exit();
		}

		$Test =& $this->{$modelName}->getModel('Test'); /* @var $Test Test */

		$Test->rel();
		$tool = $Test->read("price_test", $tool_id);
		if (! isset($tool['Test']['price_test'])) {
			$this->msgError(__d($po_domain, 'You don’t apply this tool', true), @$error_code);
			$this->redirect("/{$url_part}/{$id}/manage/", null, true);
			exit();
		}

		$error_msg = '';
		$success_msg = __d($po_domain, 'Tool has been appointed to group', true);
		$num_candidates = 0;

		$Testing =& $this->{$modelName}->getModel('Testing'); /* @var $Testing Testing */

		$candidates = $this->{$modelName}->getAllowCandidatesForTool($tool_id, $id);

		$Client =& $this->{$modelName}->getModel("Client"); /* @var $Client Client */
		$free_balance = $Client->getFreeBalance($client_id)->value;
		if (bc::lt($free_balance, bc::mul($tool['Test']['price_test'], count($candidates)))) {
			$this->msgError(__d('passes', 'Insufficient balance'.(Auth::o()->is('admin') ? "_admin" : ""), true));
			$this->redirect("/{$url_part}/{$id}/manage/", null, true);
			exit();
		}
        foreach ($candidates as $candidate) {
    		$testing_data = array(
    			'test_id' => $tool_id,
    			'candidate_id' => $candidate['Candidate']['id'],
    			'date' => Date::Unix2SQL(time()),
    			'pass_status' => 'READY',
                'password' => $Testing->getUniqueCode(9),
                'auth_link' => md5(uniqid(rand(), true))
    		);

    		if ($Testing->save($Testing->create(array($Testing->name => $testing_data)))) {
                $num_candidates++;
    		}
        }

        if ($num_candidates == 0) {
		    $error_msg = __d($po_domain, 'Tools hasn’t been appointed', true);
        }

		if (!empty($error_msg)) {
		    $this->msgError($error_msg, @$error_code);
		} else {
            $num_candidates_txt = $num_candidates.' '.__d('candidates', 'candidate_plurar_'.plurar_mode_ru($num_candidates), true);
    		$this->msgNotice(sprintf($success_msg, $num_candidates_txt));
		}

		$this->redirect("/{$url_part}/{$id}/manage/", null, true);
		exit();
    }

    function cancel_tool()
    {
        Auth::Access('admin | CANDIDATES');
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

        $conds = array();
	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
            $conds[]["`{$modelName}`.`{$PKName}`"] = $id;
	    }
        if (Auth::o()->is('client_admin')) {
            $auth_data =& Auth::o()->data();
            $conds[]["`{$modelName}`.`client_id`"] = $auth_data["client_id"];
        }
        $this->{$modelName}->rel();
	    $tmp = $this->{$modelName}->find($conds);

		if (! is_array($tmp) || !count($tmp)) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/", null, true);
			exit();
		}

	    $tool_id = null;
	    if (isset($this->params['tool_id'])) {
	        $tool_id = $this->params['tool_id'];
	    }
		if (empty($tool_id)) {
			$this->msgError(__d('tests', 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/{$id}/manage/", null, true);
			exit();
		}

		$error_msg = '';
		$success_msg = __d($po_domain, 'Tool canceled', true);

		if (! $this->{$modelName}->cancelToolFor($tool_id, $id)) {
		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
		}

		if (!empty($error_msg)) {
		    $this->msgError($error_msg, @$error_code);
		} else {
    		$this->msgNotice($success_msg);
		}

		$this->redirect("/{$url_part}/{$id}/manage/", null, true);
		exit();
    }
}

?>
